#include "circle.h"
#include <QPainter>
#include <QLineF>
#include <cmath>

Circle::Circle(const QPointF &center, qreal radius, const QColor &color)
    : MyShape(center, color), radius_(qMax(1.0, radius)) {}  // 确保最小半径为1.0

QRectF Circle::boundingRect() const
{
    return QRectF(startPoint_.x() - radius_ - hitRadius_ - penWidth_,
                  startPoint_.y() - radius_ - hitRadius_ - penWidth_,
                  2 * (radius_ + hitRadius_ + penWidth_),
                  2 * (radius_ + hitRadius_ + penWidth_));
}

void Circle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    painter->setPen(QPen(color_, penWidth_));
    painter->setBrush(QBrush(Qt::transparent));
    painter->drawEllipse(startPoint_, radius_, radius_);

    if (isSelected_ || centerHighlighted_ || edgeHighlighted_) {
        painter->setPen(QPen(Qt::blue, penWidth_));
        painter->setBrush(QBrush(Qt::blue));

        if (centerHighlighted_ || isSelected_) {
            painter->drawEllipse(startPoint_, hitRadius_/2, hitRadius_/2);
        }

        if (edgeHighlighted_ || isSelected_) {
            QPointF edgePoint(startPoint_.x() + radius_, startPoint_.y());
            painter->drawEllipse(edgePoint, hitRadius_/2, hitRadius_/2);
        }
    }
}

bool Circle::isPointNear(const QPointF &point) const
{
    qreal distance = QLineF(startPoint_, point).length();
    return std::abs(distance - radius_) <= hitRadius_ ||
           distance <= hitRadius_;
}

void Circle::highlightControlPoints(const QPointF &point)
{
    centerHighlighted_ = QLineF(startPoint_, point).length() <= hitRadius_;

    QPointF edgePoint(startPoint_.x() + radius_, startPoint_.y());
    edgeHighlighted_ = QLineF(edgePoint, point).length() <= hitRadius_;
}
